import routeState from '../store/route'
export const RoutePool = {}
export class Route {
  constructor(list) {
    this.routeList = []
    this.setRouteList(list)
    this.pool = RoutePool
  }
  setRouteList (list) {
    this.routeList.push(...list)
  }
  /**
   * 获取页面
   */
  getPage (path) {
    return RoutePool[path] || null
  }
  /**
   * 创建路由
  */
  createRoute = (list = []) => {
    this.setRouteList(list)
    this.routeList.forEach((item) => {
      const { path, component, query = {}, name } = item
      const page = new component(query)
      page.query = query
      page.visible = false
      page.path = path
      page.name = name
      const param = {
        page,
        path,
        name,
        id: page.id,
        query,
        component
      }
      RoutePool[path] = param
      RoutePool[name] = param
    })
    const { page } = this.getPage(routeState.path)
    routeState.update(page)
    return this
  }
  /**
 * 返回路由
 */
  back = () => {
    routeState.pop()
    return this
  }
  /**
   * 新增路由
   */
  push = (param) => {
    if (typeof param === 'string') {
      param = { path: param }
    }
    const { path } = param
    const { page } = this.getPage(path)
    if (routeState.path === path) {
      return this
    }
    routeState.update(page)
    return this
  }
}
export const routes = [
  {
    path: 'coins',
    name: 'coins',
    component: require('../pages/coins').default,
  },
  {
    path: 'home',
    name: 'home',
    component: require('../pages/home').default,
  }
]
/**
 * 路由实例
 */
let RouteInstance = null
/**
 * 创建路由实例
 */
export const createRoute = (route = routes) => {
  if (RouteInstance) {
    return RouteInstance
  }
  RouteInstance = new Route(route = routes)
  return RouteInstance
}
/**
 * 卸载路由实例
 */
export const destroyRoute = () => {
  RouteInstance = null
}
export default createRoute()